package band.wukong.practice.webservice.kh.sample07.nongen;

import org.testng.annotations.Test;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import java.io.IOException;
import java.net.URL;

/**
 * 用SOAP添加header
 * wsimport -d d:/ -encoding utf-8 -keep http://localhost:9000/wkp/webservice/kh/sample07?wsdl
 *
 * @author wukong(wukonggg@139.com)
 */
public class ClientTest {

    private static final String WSDL = "http://localhost:9000/wkp/webservice/kh/sample07?wsdl";
    private static final String NS = "http://www.wukong.band/practice/webservice/kh/sample07/";

    @Test
    public void add() throws IOException, SOAPException {
        // ==================== 消息部分 ====================
        SOAPMessage reqMsg = MessageFactory.newInstance().createMessage();
        SOAPEnvelope envelope = reqMsg.getSOAPPart().getEnvelope();

        SOAPHeader header = envelope.getHeader();
        if (null == header) {
            envelope.addHeader();
        }
        QName headerQName = new QName(NS,"license", "ns");
        header.addHeaderElement(headerQName).setValue("mimi");


        SOAPBody body = envelope.getBody();
        QName bodyQName = new QName(NS, "add", "ns");
        SOAPBodyElement soapBodyElement = body.addBodyElement(bodyQName);
        soapBodyElement.addChildElement("num1").setValue("2");
        soapBodyElement.addChildElement("num2").setValue("8");

        reqMsg.writeTo(System.out);
        System.out.println();


        // ==================== 调用部分 ====================
        URL url = new URL(WSDL);
        QName serviceQName = new QName(NS, "CalcServiceImplService");
        Service service = Service.create(url, serviceQName);

        QName partQname = new QName(NS, "CalcServiceImplPort");
        Dispatch<SOAPMessage> dispatch = service.createDispatch(partQname, SOAPMessage.class, Service.Mode.MESSAGE);

        System.out.println("invoking...");
        SOAPMessage respMsg = dispatch.invoke(reqMsg);
        respMsg.writeTo(System.out);
        System.out.println();
    }
}
